package filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import bean.Goods;
import dao.IndexViewMethod;

/**
 * Servlet Filter implementation class AlreadyLogin
 * 过滤用户已经登录，用户已经登录的话，在进入login页面会转向主页
 */
public class AlreadyLogin implements Filter {

	/**
	 * Default constructor.
	 */
	public AlreadyLogin() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		
		/**
		 * 获取数据库Goods最后十条纪录
		 */
		List<Goods> list;
		list = IndexViewMethod.getListGoods();// 执行具体获取方法
		request.setAttribute("ten", list);// 将结果放入request

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpSession session = httpServletRequest.getSession();// 取得session
		if (session.getAttribute("usernum") != null)// 判断session是否为空
		{
			request.getRequestDispatcher("/view/index.jsp").forward(request,
					response);// 非空，则已经登录，转入主页
			return;
		}

		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@Override
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
